﻿using Newtonsoft.Json;
using ReactiveUI;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;

namespace Common.ViewModels
{
    [Serializable]
    [JsonObject(MemberSerialization.OptIn)]
    public class ViewModelBase : ReactiveObject, IDisposable
    {
        //[JsonProperty]
        //public string UID { get; set; }=Guid.NewGuid().ToString();

        //public ReactiveCommand<Unit, Unit> ReactiveCommand1 => ReactiveCommand.Create(Dispose);

        protected List<IDisposable> m_IDisposable = new List<IDisposable>();

        public ViewModelBase()
        {
        }

        public void Dispose()
        {
            foreach (IDisposable disposable in m_IDisposable)
            {
                disposable.Dispose();
            }
            m_IDisposable.Clear();
            this.RaisePropertyChanged(
                
                );
        }
    }

    [Serializable]
    [JsonObject(MemberSerialization.OptOut)]
    public class BaseViewModel : ViewModelBase
    {

    }

    [Serializable]
    [JsonObject(MemberSerialization.OptOut)]
    public class ViewModelNotify : INotifyPropertyChanged
    {
        /// <summary>
        /// 属性值发生变化的属性
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        //protected void RaisePropertyChanged([CallerMemberName] string? propertyName = null)
        //{
        //    if (propertyName is not null)
        //    {
        //        RaisePropertyChanged(propertyName);
        //    }
           
        //}

        protected void RaisePropertyChanged<T>(Expression<Func<T>> action)
        {
            var propertyName = GetPropertyName(action);
            RaisePropertyChanged(propertyName);
        }

        private static string GetPropertyName<T>(Expression<Func<T>> action)
        {
            var expression = (MemberExpression)action.Body;
            var propertyName = expression.Member.Name;
            return propertyName;
        }

        /// <summary>
        /// 激发属性变化事件
        /// </summary>
        /// <param name="propertyName"></param>
        public void RaisePropertyChanged([CallerMemberName] string? propertyName = null)
        {
            if (propertyName is null)
            {
                return;
            }

            if (this.PropertyChanged != null)
            {
                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        //public void RaiseChanged(string propertyName)
        //{
        //    if (this.PropertyChanged != null)
        //    {
        //        this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        //    }
        //}

    }


}
